#include <semaphore.h>
#include <stdio.h>
#include <pthread.h>

#define M 10
#define N 20

sem_t sdata, sread;

int Swait(sem_t s,int a,int b)
{
    for(int i=b;i<a;i++){
        sem_wait(&s);
    }
    return 0;
}

void Ssignal(sem_t s,int n)
{
    sem_wait(&s);
    sem_post(&s);
}

void * writer(void *p){
    Swait(sdata, 1, 1);
    Swait(sread, N, 0);
    printf("Writing dataset\n");
    Ssignal (sdata, 1);
    return NULL;
}

void * reader(void *p){
    while(Swait(sdata, 1, 0) || Swait(sread,1,1));
    printf("Reading dataset\n");
    Ssignal(sread, 1);
    return NULL;
}


int main(void)
{
    sem_init(&sdata, 0, 1); 
    sem_init(&sread, 0, N);    
    pthread_t tid[M], tid2[M];
    for(int i=0; i<M; i++) 
        pthread_create(&tid[i], NULL, writer, NULL);
    for(int i=0; i<M; i++) 
        pthread_create(&tid2[i], NULL, reader, NULL);
    sem_destroy(&sdata); 
}
